import 'dart:convert';
import 'dart:developer';
import 'dart:io';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter_app_update/azhon_app_update.dart';
import 'package:flutter_app_update/flutter_app_update.dart';
import 'package:get/get.dart';
import 'package:install_plugin_v2/install_plugin_v2.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:ball_lion/entity/other/app_update_entity.dart';
import 'package:ball_lion/utils/sp_utils.dart';
import 'package:ball_lion/utils/toast_utils.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/update_check_sheet.dart';

import 'package:ball_lion/server/api/other_api.dart';
import 'package:ball_lion/widgets/select_bottomsheet.dart';
import 'app_config.dart';

class UpdateUtils {
  static AppUpdateEntity? updateInfo;
  static PackageInfo? packageInfo;

  static Future getInfo() async {
    packageInfo = await PackageInfo.fromPlatform();
    updateInfo = await OtherApi.checkUpdate(packageInfo?.version ?? "");
    // AzhonAppUpdate.listener((map) {
    //   if (map['type'] == "done") {
    //     SpUtils.apkPath = map['apk'];
    //     Get.bottomSheet(const UpdateCheckSheet());
    //   }
    // });
    checkUpdate();
  }

  static Future checkUpdate() async {
    updateInfo = await OtherApi.checkUpdate(packageInfo?.version ?? "");
    if (updateInfo?.needUpdate == 1) {
      var connect = await Connectivity().checkConnectivity();
      if (SpUtils.autoDownload ??
          true &&
              SpUtils.apkPath.noValue &&
              connect.contains(ConnectivityResult.wifi)) {
        AzhonAppUpdate.update(UpdateModel(
            updateInfo?.apkUrl ?? "", "球狮体育.apk", "ic_launcher", "",
            showNotification: false,
            showBgdToast: false,
            jumpInstallPage: false));
      } else {
        if (connect.contains(ConnectivityResult.none)) {
          Toast.text("当前无网络链接");
          return;
        }
        Get.bottomSheet(const UpdateCheckSheet(), isDismissible: false);
      }
    }
  }

  static Future<int> update() async {
    if (SpUtils.apkPath.hasValue) {
      final s = !AppConfig.config.isDebug
          ? 0
          : await Get.bottomSheet(const SelectBottomSheet(["安装", "删除"]));
      if (s == 0) {
        try {
          InstallPlugin.installApk(SpUtils.apkPath!, "net.qiushisports.app");
        } catch (e) {
          log(e.toString());
        }
        return 2;
      } else if (s == 1) {
        try {
          File(SpUtils.apkPath!).deleteSync();
        } catch (e) {
          log(e.toString());
        }
        SpUtils.apkPath = null;
        return 1;
      }
    } else {
      AzhonAppUpdate.update(UpdateModel(
          updateInfo?.apkUrl ?? "", "球狮体育.apk", "ic_launcher", "",
          showNotification: true, showBgdToast: true, jumpInstallPage: false));
      return 0;
    }
    return 0;
  }

  static Future cancel() async {
    AzhonAppUpdate.cancel;
  }
}
